/*
 * Created on Fri Oct 06 2017
 * @flow
 * Copyright (c) 2017 jianglinjie
 */
'use strict';

import RegisterService from '../../src/services/register';
import CaptchaService from '../../src/services/captcha';
import { RegisterType } from '../../src/constants';
import { CaptchaBusiness } from '../../src/constants';
import { getCaptchaRedisKey } from '../../src/utils/CaptchaUtils';
import redis from '../../src/redis';
import AuthService from '../../src/services/auth';
import { LoginType } from '../../src/constants';
import hasha from 'hasha';

export async function registerWithUserName(userName, password) {
  let registerParam = {
    userName: userName,
    pwd: password
  }
  let result = await RegisterService.register(RegisterType.USERNAME_PWD, registerParam);
  return result;
}

export async function registerWithPhone(phone, password) {  
  let captchaResult = await CaptchaService.request({
    phone: phone,
    business: CaptchaBusiness.REGISTER
  });

  let redisKey = getCaptchaRedisKey(phone, CaptchaBusiness.REGISTER);
  let captcha = await redis.getAsync(redisKey);

  if (captcha !== captchaResult.captcha) {
    throw new Error('register captcha not equal to redis cache');
  }

  let registerParam = {
    phone: phone,
    pwd: password,
    captcha: captchaResult.captcha
  }

  let result = await RegisterService.register(RegisterType.PHONE_PWD_CAPTCHA, registerParam);

  return result;
}

export async function loginWithAccount(account, password) {  
  let encryptPwd = hasha(password, { algorithm: 'md5' });
  let result = await AuthService.login(LoginType.ACCOUNT_ENCRYPTPWD, {
    account: account, //用户名或者手机
    encryptPwd: encryptPwd
  });

  return result;
}

export async function loginWithPhone(phone) {
  let captchaResult = await CaptchaService.request({
    phone: phone,
    business: CaptchaBusiness.LOGIN
  });

  let redisKey = getCaptchaRedisKey(phone, CaptchaBusiness.LOGIN);
  let captcha = await redis.getAsync(redisKey);
  if (captcha !== captchaResult.captcha) {
    throw new Error('login captcha not equal to redis cache');    
  }

  let result = await AuthService.login(LoginType.PHONE_CAPTCHA, {
    phone: phone,
    captcha: captchaResult.captcha
  });
  
  return result;
}

